package com.ming.user.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import com.ming.common.entity.ResponseCode;
import com.ming.common.entity.ResultData;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname SentinelConfig
 * @Description TODO
 * @Date 2021/1/11 12:36
 * @Created by yanming.fu
 */
@Configuration
public class SentinelConfig  implements UrlBlockHandler {


    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        // BlockException 异常接口，其子类为Sentinel五种规则异常的实现类
        // AuthorityException 授权异常
        // DegradeException 降级异常
        // FlowException 限流异常
        // ParamFlowException 参数限流异常
        // SystemBlockException 系统负载异常
        ResultData data = new ResultData();
        if (e instanceof FlowException) {
            data = ResultData.fail(ResponseCode.ERROR.val(), "接口被限流了。");
        } else if (e instanceof DegradeException) {
            data = ResultData.fail(ResponseCode.ERROR.val(), "接口被降级了。");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(data));
    }

}
